import React, { useState } from 'react'
import city from './city.json'
import { IndexBar, Cell, Search } from 'react-vant'
import { useNavigate } from 'react-router-dom'

const CityList = () => {
	const navigate = useNavigate();
	return (
		<IndexBar>
			{
				city.map((v, i) => {
					return (
						<div key={i}>
							<IndexBar.Anchor index={v.code} />
							{v.cityList.map((v, i) => {
								return <Cell title={v} key={i} onClick={() => {
									localStorage.setItem('city', v);
									navigate(-1)
								}} />
							})}
						</div>
					)
				})
			}
		</IndexBar >
	)
}

const Index = () => {
	const [value, setValue] = useState('')
	const [isSearch, setIsSearch] = useState(false)
	const [searchList, setSearchList] = useState<string[]>([])
	const navigate = useNavigate();
	const onSearch = () => {
		// 切换状态
		setIsSearch(true);
		// 搜索
		const searchList = city.reduce((p, n) => {
			return p.concat(n.cityList.filter(v => v.includes(value)))
		}, [] as string[])
		// 保存数据
		setSearchList(searchList)

	}


	return (
		<div>
			<Search value={value} onChange={value => setValue(value)} onSearch={() => onSearch()} onClear={() => setIsSearch(false)}></Search>
			{isSearch ? <div>
				{
					searchList.map((v, i) => {
						return <Cell title={v} key={i} onClick={() => {
							localStorage.setItem('city', v);
							navigate(-1)
						}} />
					})
				}
			</div> : <CityList></CityList>}
		</div >
	)
}

export default Index